<template>
    <el-button color="#00b794" :icon="Document" round @click="showform()">{{ $t('Excel导入') }}</el-button>
    <el-dialog v-model="FormVisible" style="padding: 0" :show-close="false" fullscreen>
        <template #header="{ close }">
            <el-row style="padding: 10px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                <el-col :span="6">
                    <span style="font-size: 20px; font-weight: 1000; color: white">
                        <el-icon><Document /></el-icon>{{ title }}{{ $t('Excel导入') }}
                    </span>
                </el-col>
                <el-col :span="18">
                    <div style="float: right">
                        <el-button :icon="Back" @click="close" round>{{ $t('返回') }}</el-button>
                        <el-button color="#2587eb" :icon="Check" round @click="comfirmimput()">{{ $t('确定导入') }}</el-button>
                    </div>
                </el-col>
            </el-row>
        </template>
        <el-row>
            <el-text style="margin-left: 10px" truncated> 1、 <el-button link type="primary" style="font-size: 16px" @click="exportEvent()">{{ $t('【下载导入模板】') }}</el-button> <br /></el-text>
        </el-row>
        <el-row style="margin-top: 5px">
            <el-text style="margin-left: 10px; font-size: 16px" truncated> 2、{{ $t('确认导入模板格式,模板格式如下方列表标题,如需调整,请点击【配置】调整后下方列表标题同步刷新') }}<br /></el-text>
        </el-row>
        <el-row style="margin-top: 5px">
            <div style="width: 100%; display: flex; flex-wrap: nowrap">
                <el-text style="margin-left: 10px; font-size: 16px" truncated> 3、{{ $t('按照模板格式整理好表格,然后【上传数据】') }}</el-text>
            </div>
        </el-row>
        <el-row style="margin-top: 5px">
            <el-text style="margin-left: 10px; font-size: 16px" truncated> 4、{{ $t('导入结果预览,确认无误,则点击右上角的【确认导入】') }}<br /> </el-text>
        </el-row>
        <el-row>
            <el-text style="margin-left: 10px; font-size: 16px" truncated> 5、<el-checkbox style="font-size: 16px" v-model="iscover" :label="$t('否覆盖导入')" size="large" /></el-text>
        </el-row>
        <el-row style="padding: 10px">
            <el-col :span="24">
                <!-- <el-button style="float: right" color="#0176bb" :icon="Setting" circle></el-button> -->
                <!-- <UiSet :type="3" :index="index" :Prop="uiSectionList" :comid="componentId"></UiSet> -->
                <el-upload style="float: right;margin-right:10px" action="#" :show-file-list="false" :limit="1" :on-change="handleFileChange" :before-upload="beforeUpload">
                    <el-button  type="primary" style="font-size: 17px"> {{ $t('上传数据') }} </el-button>
                </el-upload>
            </el-col>
        </el-row>
        <div style="width: 100%; overflow-x: auto">
            <el-table-v2 :columns="columns" :data="tabledata" :width="tablewidth" :height="640" fixed />
        </div>
    </el-dialog>
</template>

<script lang="ts" setup>
import { httpSend } from '@/utils/api';
import { useI18n } from 'vue-i18n';
import { Document, Setting, Check, Back } from '@element-plus/icons-vue';
import { getCurrentInstance,ref, toRefs} from 'vue';
import { useshareStore } from '@/store'; /*pina管理*/
import * as XLSX from 'xlsx'; /*excel操作*/
const { t } = useI18n(); //多语言
let tabletitle: any = [];
interface FormDatabaseProps {
    title?: string;
    index?: number;
    comid?: string;
    Prop?: any;
    isgrant?: boolean;
}
const base = withDefaults(defineProps<FormDatabaseProps>(), {
    title: '',
    index: 0,
    comid: null,
    Prop: null,
    isgrant: true,
});

const {title, Prop} = toRefs(base);
const index=base.index;
const comid=base.comid+'excel'+index;
const FormVisible = ref(false);
const loading = ref(false);
const tablewidth = ref(0);
const iscover = ref(false);
let basecolumns = [];
let columns = [];
let tabledata = ref([]);
const { appContext } = getCurrentInstance();
const ElMessage = appContext.config.globalProperties.$ElMessage;
//显示表单
const showform = async () => {
    emit('before-click');
    if(!base.isgrant){
        return;
    }
    tabledata.value=[];
    getuiset();
    FormVisible.value = true;
};
const closeform = () => {
    FormVisible.value = false;
};
defineExpose({ closeform });
//获取配置数据
const getuiset = async () => {
    loading.value = true;
    let comdata = [];
    const fd = new FormData();
    let data = { comid: comid, userid: null };
    fd.append('param', JSON.stringify(data));
    const res = await httpSend('getComUiSet', fd, false);
    //未启用获取自定义配置功能
    if (res && res.code == 1) {
        if (res.data && res.data.length > 0) {
            //如果有保存过,加载保存后数据
            let data = JSON.parse(res.data[0]['setjson']);
            // 如果数据依然是字符串,则需要再解析一次
            if (typeof data === 'string') {
                data = JSON.parse(data); // 第二次解析
            }
            if (data) {
                Object.assign(basecolumns, data);
                Object.assign(columns, data);
            }
        }else{
            //初始加载默认数据
            basecolumns = Prop.value[index]['tableProps']
                .filter((item) => item.prop !== 'checked' && item.prop !== 'action')
                .map((v) => {
                    return {
                        key: v.prop,
                        dataKey: v.prop,
                        title: I(v.label,v.labeleng),
                        width: v.width,
                        visible: v.visible
                    };
                });
            columns = Object.assign(basecolumns);
            basecolumns.forEach((v) => {
                tablewidth.value += Number(v.width);
            });
        }
    }
    loading.value = false;
};

const emit = defineEmits(['before-click', 'comfirmimput']);
//确定导入
const comfirmimput=()=>{
    if(!tabledata.value || tabledata.value.length==0){
        ElMessage.warning(t('没有需要导入的数据'));
        return;
    }
    if (iscover.value) {
        const confirmation = window.confirm(t('您勾选了覆盖,是否确定覆盖导入?'));
        if (!confirmation) {
            return false;
        }
    }
    emit('comfirmimput', tabledata.value,iscover.value);
    //FormVisible.value = false;
}

const isFileProcessed = ref(false); // 防止重复处理文件
// 在上传之前确保只处理一次文件
const beforeUpload = (file: File) => {
    // 如果文件已经处理过,阻止上传
    if (isFileProcessed.value) {
        return false;
    }
    return true;
};
//excel导入后操作
const handleFileChange = (file: any) => {
    if (isFileProcessed.value) {
        console.log('文件已处理');
        return; // 如果文件已处理,跳过
    }
    isFileProcessed.value = true; // 标记文件已经处理
    const fileObj = file.raw;
    // 检查文件对象是否有效
    if (!fileObj || !(fileObj instanceof Blob)) {
        ElMessage.error(t('无效的文件'));
        return;
    }
    // 检查文件类型
    const fileName = fileObj.name.toLowerCase();
    const types = ['xlsx', 'xls'];
    if (!types.some((type) => fileName.endsWith(`.${type}`))) {
        ElMessage.error(t('仅支持 xlsx 或 xls 格式的文件'));
        return;
    }
    // 使用 FileReader 读取文件
    const reader = new FileReader();
    reader.onload = function (e) {
        if (e.target && e.target.result) {
            const data = new Uint8Array(e.target.result as ArrayBuffer);
            const workbook = XLSX.read(data, { type: 'array' });
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            // 将工作表转换为 JSON 数据
            const jsonData = XLSX.utils.sheet_to_json(worksheet);
            //表格数据
            const formattedData = jsonData.map((row) => {
                // 创建一个新的对象
                const newRow = {};
                columns.forEach((v) => {
                    if (v.key != 'action' && v.key != 'checked'  && v.visible) {
                        newRow[v.key] = !!row[v.title] ? row[v.title] : null;
                    }
                });
                return newRow; // 返回新创建的对象
            });
            tabledata.value = formattedData;
        }
        isFileProcessed.value = false;
    };
    // 确保 fileObj 是 Blob 类型
    if (fileObj instanceof Blob) {
        reader.readAsArrayBuffer(fileObj);
    } else {
        ElMessage.error(t('无法读取文件,请重试'));
    }
};

//导出excel模版
const exportEvent = () => {
        // 创建一个新的对象
        const newRow = {};
        columns.forEach((v) => {
            if (v.visible && v.key != 'action' && v.key != 'checked') {
                newRow[v.title] ='';
            }
        });
    // 使用自定义标题和数据生成工作表
    const ws = XLSX.utils.json_to_sheet([newRow]); // { header }
    // 创建一个新的工作簿
    const wb = XLSX.utils.book_new();
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    // 使用文件名导出 Excel 文件
    XLSX.writeFile(wb, title.value+t('模版')+'.xlsx');
};

const I = (label, labeleng) => {
    if (labeleng && localStorage.getItem('locale') == 'en') {
        return labeleng;
    }
    return t(label);
};
</script>

<>
